package net.xdclasss.demo_project.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import net.xdclasss.demo_project.domain.User;
import net.xdclasss.demo_project.service.impl.UserServiceImpl;
import net.xdclasss.demo_project.utils.JsonData;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登录过滤工具类
 */
// @WebFilter(urlPatterns = {"/api/v1/pri/*"})
public class LoginFilter implements Filter {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init=====");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("doFilter=====");

        HttpServletRequest req = (HttpServletRequest)servletRequest;
        HttpServletResponse resp = (HttpServletResponse)servletResponse;
        String token = req.getHeader("token");
        if (StringUtils.isEmpty(token)){
            token = req.getParameter("token");
        }
        if (!StringUtils.isEmpty(token)){
            // 判断token是否合法
            User user = UserServiceImpl.sessionMap.get(token);
            if (user != null){
                filterChain.doFilter(servletRequest,servletResponse);
            } else {
                rederJson(resp,JsonData.bulidError(-3,"登录失败，token失效"));

            }
        }else {
            rederJson(resp,JsonData.bulidError(-4,"未登录"));
        }
    }

    public JsonData rederJson(HttpServletResponse resp, JsonData jsonData){
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("application/json");

        try(PrintWriter writer = resp.getWriter()) {
            String strJson = objectMapper.writeValueAsString(jsonData);
            writer.print(strJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonData;
    }


    @Override
    public void destroy() {
        System.out.println("destroy=====");

    }
}
